I have added a "Add new person" button in a select2 dropdownlist
The select2 code looks like this:
$('#subFundSelection').select2({
width: '100%',
placeholder: 'Select a sub-fund',
ajax: {
url: '/FundInfo/SearchLegalEntities',
type: 'GET',
dataType: 'json',
delay: 250,
allowClear: true,
data: function (params) {
return {
searchTerm: params.term
};
},
processResults: function (data) {
return {
results: $.map(data.legalEntities, function (obj) {
return { id: obj.Id, text: obj.Text };
})
};
},
},
minimumInputLength: 2
}).on('select2:open', () => {
$(".select2-results:not(:has(button))").append('<button id="newPersonButton" style="width: 100%" type="button" class="btn btn-primary" onClick="CreateLegalEntity()">+ Add a new person</button>')
})
A button is well added to the dropdownlist (I cant add a picture sorry)
and when I click this "Add new person" button I open a modal.
function CreateLegalEntity() {
$('#CreateLegalEntityModal').modal('show');
}
Everything work fine, instead of the fact that the dropdown list doesnt close after the click and it appears in the top of the modal, until I click somewhere else in the screen.
Sorry for not attaching screenshots but the website doesnt allow me.
I have tried:
$(this).blur()
$(".select2").trigger('blur')
$(".select2").trigger('change')
From the documentation of SELECT2 here Methods | Select2
The close method will cause the dropdown menu to close, hiding the selectable options:
$('#subFundSelection').select2('close');
Should do what your looking for
EDIT
You should be calling the .select2('close') method from the same identifier your are initially creating the element .select2({params});
eg: $('#div1').select2() so it should be $('#div1').select2('close')